import { ref, reactive, onMounted, type Ref, watch } from "vue";
import { useDataSyncStore } from "@/store/modules/dataSync";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { ChannelMemberItem } from "./type/channelMembersTypes";
import type { FormItemProps } from "./type/channelMembersTypes";
import { h } from "vue";
import channelMembersForm from "../componentsForm/channelMembersForm.vue";

export function useChannelMembersTable(
  tableRef: Ref,
  lesseeId: number,
  dealerId: number
) {
  const form = reactive({
    channelName: "",
    name: "",
    priority: "",
    SearchTerm: "",
    OrderBy: "",
    channelId: ""
  });
  const formRef = ref();
  const dataList = ref<ChannelMemberItem[]>([]);
  const loading = ref(true);
  const selectedNum = ref(0);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const channelOptions = ref<Array<{ value: number; label: string }>>([]);
  const userOptions = ref<Array<{ value: number; label: string }>>([]);
  // 列表列定义
  const columns = [
    {
      label: "频道名称",
      prop: "ChannelName",
      minWidth: 120
    },
    {
      label: "用户名称",
      prop: "UserName",
      minWidth: 100
    },
    {
      label: "类型",
      prop: "Type",
      minWidth: 80,
      formatter: ({ Type }) => {
        return Type === 0 ? "白名单" : Type === 1 ? "黑名单" : "未知";
      }
    },
    {
      label: "加入时间",
      prop: "CreateTime",
      minWidth: 160
    },
    {
      label: "操作",
      fixed: "right",
      width: 140,
      slot: "operation"
    }
  ];
  // 获取、搜索频道成员列表
  function onSearch() {
    loading.value = true;
    const params = {
      PageIndex: pagination.currentPage,
      PageSize: pagination.pageSize,
      OrderBy: form.OrderBy,
      IsDesc: false,
      SearchTerm: form.SearchTerm,
      tenantId: lesseeId,
      channelId: form.channelId ? Number(form.channelId) : undefined,
      name: form.name ? form.name : undefined
    };
    console.log(params);
    http
      .get(changeHttpLink("/api/ChannelMember"), {
        params
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          dataList.value = res.Data.Items || [];
          pagination.total = res.Data.TotalCount || 0;
          console.log(dataList.value);
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }
  //获取表单频道下拉框
  function getChannelOptions() {
    http
      .get(changeHttpLink("/api/Channel"), {
        params: {
          tenantId: lesseeId
        }
      })
      .then((res: any) => {
        if (res.Success) {
          // 将获取的频道列表转换为下拉列表选项
          channelOptions.value = res.Data.Items.map((item: any) => ({
            label: item.Name,
            value: item.Id
          }));
          channelOptions.value.unshift({
            label: "默认频道",
            value: 0
          });
          // 添加默认选项
          //console.log("频道列表数据:", channelOptions.value);
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        message(err.message, { type: "error" });
      });
  }
  //获取表单用户下拉框
  function getUserOptions() {
    http
      .get(changeHttpLink("/api/User"), {
        params: {
          PageIndex: 1,
          PageSize: 500,
          tenantId: lesseeId
        }
      })
      .then((res: any) => {
        if (res.Success) {
          // 将获取的用户列表转换为下拉列表选项
          console.log("用户列表数据:", res.Data);
          userOptions.value = res.Data.Items.map((item: any) => ({
            label: item.Name,
            value: item.Id
          }));
          userOptions.value.unshift({
            label: "默认用户",
            value: 0
          });
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        message(err.message, { type: "error" });
      });
  }
  // 新增频道成员（已移除修改功能）
  function openDialog(title: string, row: any = null) {
    //const id = row?.id ?? 0;
    // 在函数内部定义formRef，确保作用域正确
    const formRef = ref();

    addDialog({
      title: `${title}频道成员`,
      props: {
        formInline: {
          id: row?.Id ?? 0,
          dealerId: dealerId,
          tenantId: lesseeId,
          channelId:
            row?.ChannelId ?? (form.channelId ? Number(form.channelId) : 0),
          userId: row?.UserId ?? 0,
          priority: row?.Priority ?? 0,
          type: row?.Type ?? 0
        },
        title: title,
        channelOptions: channelOptions.value,
        userOptions: userOptions.value
      },
      width: "640px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(channelMembersForm, {
          ref: formRef,
          // 正确传递formInline属性
          formInline: {
            id: row?.Id ?? 0,
            dealerId: dealerId,
            tenantId: lesseeId,
            channelId:
              row?.ChannelId ?? (form.channelId ? Number(form.channelId) : 0),
            userId: row?.UserId ?? 0,
            priority: row?.Priority ?? 0
          },
          title: title,
          channelOptions: channelOptions.value,
          userOptions: userOptions.value
        }),

      beforeSure: (done, { options }) => {
        // 修复获取表单引用的方式
        const FormRef = formRef.value?.getRef();
        if (!FormRef) {
          message("表单加载失败，请重试", { type: "error" });
          return;
        }

        const curData = options.props.formInline as FormItemProps;

        function chores() {
          message(
            `您${title}了频道成员ID为【${curData.id || "新创建"}】的这条数据`,
            {
              type: "success"
            }
          );
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }

        FormRef.validate(valid => {
          if (valid) {
            loading.value = true;
            // 使用getFormData方法获取处理后的表单数据
            const formData = formRef.value?.getFormData();
            if (!formData) {
              message("获取表单数据失败，请重试", { type: "error" });
              loading.value = false;
              return;
            }

            console.log(formData);
            if (title === "创建") {
              // 处理userId字符串，拆分为数组并为每个userId创建一个items对象
              const userIds = formData.userId ? formData.userId.split(",") : [];

              if (userIds.length === 0) {
                message("请至少选择一个用户", { type: "error" });
                loading.value = false;
                return;
              }

              // 先获取当前频道的成员列表，检查用户ID唯一性
              const checkParams = {
                PageIndex: 1,
                PageSize: 9999, // 获取所有成员
                tenantId: lesseeId,
                channelId: formData.channelId
              };

              http
                .get(changeHttpLink("/api/ChannelMember"), {
                  params: checkParams
                })
                .then((checkRes: any) => {
                  if (checkRes.Success) {
                    const existingUserIds = checkRes.Data.Items.map(item =>
                      item.UserId.toString()
                    );
                    const duplicateUsers = [];
                    const validUserIds = [];

                    // 检查每个要添加的用户ID是否已存在
                    userIds.forEach(userId => {
                      const trimmedUserId = userId.trim();
                      if (existingUserIds.includes(trimmedUserId)) {
                        // 找到对应的用户名
                        const userName =
                          userOptions.value.find(
                            user => user.value.toString() === trimmedUserId
                          )?.label || `用户ID: ${trimmedUserId}`;
                        duplicateUsers.push(userName);
                      } else {
                        validUserIds.push(trimmedUserId);
                      }
                    });

                    // 如果有重复用户，提示错误
                    if (duplicateUsers.length > 0) {
                      message(
                        `以下用户已在频道名单内：${duplicateUsers.join("、")}`,
                        { type: "error" }
                      );
                      loading.value = false;
                      return;
                    }

                    // 如果没有有效用户ID，提示错误
                    if (validUserIds.length === 0) {
                      message("所有选择的用户都已在频道名单内", {
                        type: "error"
                      });
                      loading.value = false;
                      return;
                    }

                    // 为每个有效的userId创建一个items对象
                    const items = validUserIds.map(userId => ({
                      dealerId: dealerId,
                      tenantId: lesseeId,
                      channelId: formData.channelId,
                      userId: parseInt(userId),
                      type: formData.type
                    }));

                    const batchData = { items };

                    // 执行批量创建
                    http
                      .post(changeHttpLink("/api/ChannelMember/batch-create"), {
                        data: batchData
                      })
                      .then((res: any) => {
                        if (res.Success) {
                          chores();
                        } else {
                          message(res.Message, { type: "error" });
                        }
                        loading.value = false;
                      })
                      .catch(err => {
                        loading.value = false;
                        message(err.message, { type: "error" });
                      });
                  } else {
                    message(checkRes.Message, { type: "error" });
                    loading.value = false;
                  }
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            }
          }
        });
      }
    });
  }

  // 删除频道成员
  function handleDelete(row: ChannelMemberItem) {
    ElMessageBox.confirm(`是否确认删除ID为${row.Id}的频道成员`, "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true
    })
      .then(() => {
        loading.value = true;
        http
          .request(
            "delete",
            changeHttpLink(
              `/api/ChannelMember/${row.ChannelId}/user/${row.UserId}`
            ),
            {
              data: {
                channelId: row.ChannelId,
                userId: row.UserId
              }
            }
          )
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`您删除了ID为${row.Id}的频道成员`, {
                type: "success"
              });
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 批量删除
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const listIds = curSelected.map(item => item.Id);

    ElMessageBox.confirm(
      `是否确认删除选中的${listIds.length}条数据`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(() => {
        loading.value = true;
        http
          .post(changeHttpLink("/api/ChannelMember/batch-delete"), {
            data: { ids: listIds }
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`已删除选中的${listIds.length}条数据`, {
                type: "success"
              });
              tableRef.value.getTableRef().clearSelection();
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 分页大小变化
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    onSearch();
  }

  // 处理当前页变化
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  // 多选框变化
  function handleSelectionChange(val: ChannelMemberItem[]) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }

  // 多选框反选
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }

  // 重置表单
  function resetForm(formEl: any) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  // 设备检测
  function deviceDetection() {
    return window.innerWidth <= 1024;
  }

  onMounted(() => {
    // 初始化加载数据
    onSearch();
    getChannelOptions();
    getUserOptions();

    // 监听全局数据更新
    const dataSyncStore = useDataSyncStore();
    watch(
      () => dataSyncStore.userDataTimestamp,
      () => {
        console.log(
          "[ChannelMembers] User data updated, refreshing user options..."
        );
        getUserOptions();
      }
    );
  });

  return {
    form,
    formRef,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleDelete,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange,
    userOptions
  };
}
